package com.xfhy.selectcity.select;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ludashi.framework.adapter.BaseQuickAdapter;
import com.ludashi.framework.base.BaseFrameActivity;
import com.ludashi.framework.utils.log.LogUtil;
import com.xfhy.selectcity.R;
import com.xfhy.selectcity.adapter.BaseAreaType;
import com.xfhy.selectcity.adapter.SearchAreaAdapter;
import com.xfhy.selectcity.adapter.SelectProvinceAdapter;
import com.xfhy.selectcity.data.Area;
import com.xfhy.selectcity.select.viewmodel.SelectProvinceViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * 选则省份
 */
public class SelectProvinceActivity extends BaseFrameActivity implements BaseQuickAdapter.OnItemClickListener, TextWatcher {

    private final static String[] PERMISSIONS = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private static final int OPEN_SET_REQUEST_CODE = 100;

    private RecyclerView mRvSelectProvince, mRvSearchArea;
    private SelectProvinceViewModel mSelectProvinceViewModel;
    private List<BaseAreaType> mAreaItems = new ArrayList<>();
    private SelectProvinceAdapter mSelectProvinceAdapter;
    private SearchAreaAdapter mSelectAreaAdapter;
    private EditText mEtSearch;

    @Override
    protected void onSafeCreate(Bundle savedInstanceState) {
        super.onSafeCreate(savedInstanceState);
        setContentView(R.layout.activity_select_province);

        initView();
        initData();
        initPermissions();

        //检查用户是否已经授权定位权限,如果没有授权,则弹窗提示开启授权
        /*if (PermissionChecker.checkPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION,
                Process.myPid(), Process.myUid(), getPackageName()) != PermissionChecker.PERMISSION_GRANTED) {
            LogUtil.d("xfhy_area", "未授权");
        } else {
            LogUtil.d("xfhy_area", "已授权");
        }*/
    }

    private void initView() {
        mRvSelectProvince = findViewById(R.id.rv_select_province);
        mRvSearchArea = findViewById(R.id.rv_search_area);
        mEtSearch = findViewById(R.id.et_select_province_search);
        mEtSearch.addTextChangedListener(this);

        mSelectProvinceAdapter = new SelectProvinceAdapter(null);
        mRvSelectProvince.setAdapter(mSelectProvinceAdapter);

        mSelectAreaAdapter = new SearchAreaAdapter(null);
        mRvSearchArea.setAdapter(mSelectAreaAdapter);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                BaseAreaType baseAreaType = mAreaItems.get(position);
                if (baseAreaType.getItemType() == BaseAreaType.AREA_TITLE) {
                    return 4;
                }
                return 1;
            }
        });
        mRvSelectProvince.setLayoutManager(gridLayoutManager);
    }

    private void initData() {
        mSelectProvinceViewModel = new ViewModelProvider(this).get(SelectProvinceViewModel.class);
        mAreaItems = mSelectProvinceViewModel.initHotData();
        mSelectProvinceAdapter.replaceData(mAreaItems);
        mSelectProvinceAdapter.setOnItemClickListener(this);
    }

    private void initPermissions() {
        if (lacksPermission(PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, OPEN_SET_REQUEST_CODE);
        } else {
            startLocate();
        }
    }

    public boolean lacksPermission(String[] permissions) {
        for (String permission : permissions) {
            //判断是否缺少权限，true=缺少权限
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == OPEN_SET_REQUEST_CODE) {
            if (grantResults.length > 0) {
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        //未拥有相应权限

                        //是否勾选了不再提示
                        boolean checkDonTPromptAgain = false;
                        for (String permission : permissions) {
                            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                                //勾选了
                                checkDonTPromptAgain = true;
                                break;
                            }
                        }
                        if (checkDonTPromptAgain) {
                            //todo xfhy 弹窗 然后 让用户去设置界面开启
                            LogUtil.d("xfhy_area", "弹窗 然后 让用户去设置界面开启");
                        } else {
                            //只是单次拒绝了权限  重新申请权限
                            LogUtil.d("xfhy_area", "只是单次拒绝了权限");
                            initPermissions();
                        }
                        return;
                    }
                }
                startLocate();
            } else {
                //todo xfhy 弹窗 然后 让用户去设置界面开启
                Toast.makeText(this, "未拥有相应权限", Toast.LENGTH_LONG).show();
                LogUtil.d("xfhy_area", "grantResults.length<0");
            }
        }
    }

    private void startLocate() {
        //todo xfhy 开始定位
        LogUtil.d("xfhy_area", "开始定位");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
        BaseAreaType baseAreaType = mAreaItems.get(position);
        if (baseAreaType.getItemType() != BaseAreaType.AREA_ITEM) {
            return;
        }
        //判断一下 自治区 直辖市  港澳台 -> 直接去选择区县
        switch (baseAreaType.content) {
            case "定位":
                break;
            case "北京":
            case "上海":
            case "天津":
            case "重庆":
            case "香港":
            case "澳门":
            case "台湾":
                //热门城市
            case "广州":
            case "深圳":
            case "杭州":
            case "成都":
                SelectAreaActivity.startSelectAreaActivity(this, baseAreaType.content);
                break;
            default:
                SelectCityActivity.startSelectCityActivity(this, baseAreaType.content);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    private final Observer<List<Area>> mKeyChangeObserver = new Observer<List<Area>>() {
        @Override
        public void onChanged(List<Area> areas) {
            LogUtil.d("xfhy_area", areas.toString());
            mSelectAreaAdapter.replaceData(areas);
        }
    };

    @Override
    public void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(s.toString())) {
            mSelectAreaAdapter.replaceData(new ArrayList<>());
            mRvSearchArea.setVisibility(View.GONE);
            return;
        }
        mRvSearchArea.setVisibility(View.VISIBLE);
        mSelectProvinceViewModel.searchAreasByKey(s.toString()).observe(this, mKeyChangeObserver);
    }
}